package com.ghsc.ghxc.jsb.ui.message.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.flyco.roundview.RoundTextView
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityChatListBinding
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.ui.message.bean.Data
import com.ghsc.ghxc.jsb.ui.message.bean.UserRyResult
import com.ghsc.ghxc.jsb.ui.message.view.PayPwdPopViiew
import com.ghsc.ghxc.jsb.ui.message.view.RouterUtils
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.ghsc.ghxc.jsb.view.NotDataView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：ChatListActivity
 * 创建时间：2024/5/9 22:53
 * 创建人 @author： xiaolin
 * 描述 ：Todo...我的好友
 */
class ChatListActivity : BaseVMActivity<ChatViewModel, ActivityChatListBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_chat_list
    }

    override fun attachVMClass(): Class<ChatViewModel>? {
        return ChatViewModel::class.java
    }

    private val mAdapter: ChatListAdapter by lazy { ChatListAdapter(1) }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null
    var keyword:String=""

    var itemPosition =-1

    var bundle : Bundle?=null
    var name :String=""
    var classify_id :Int=0


    var chatDataBean : Data?=null



    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        bundle=intent.extras
        name=bundle!!.getString("name","")
        classify_id= bundle!!.getInt("classify_id")
        binding.run {
            tvBtnCheck.visibility= View.VISIBLE
            tvBtnCheck.text="确定(0)"
            topLeftView.setOnClickListener {
                hideKeyboard(etSearch)
                finish()
            }
            topTitle.text="选择联系人"
            tvBtnNext.setOnClickListener {
                if (TextUtils.isEmpty(binding.etSearch.text)){
                    showToast("请输入邀请码/手机号")
                }else{
                    pageNo = 1
                    getListData()
                }
            }
            etSearch.isFocusable = true
            etSearch.isFocusableInTouchMode = true
            etSearch.requestFocus()
            etSearch.setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = binding.etSearch.text.toString().trim()
                    if (!TextUtils.isEmpty(keyword)) {
                        binding.etSearch.clearFocus()
                        hideKeyboard(binding.etSearch)
                        pageNo = 1
                        getListData()
                    }
                }
                false
            }
        }
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
//        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(this, binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.addChildClickViewIds(R.id.tvBtnNext,R.id.imgCheck)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            //item里面某个按钮事件
            when(view.id){
                R.id.tvBtnNext ->{
//                    if (mAdapter.getItem(position).status ==-2){
//                        itemPosition=position
//                        val map: HashMap<String, Any> = HashMap()
//                        map["fuid"] = mAdapter.getItem(position).uid
//                        map["ptype"] = 1
//                        //1是同意
//                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onActFriendMethod(it1) }
//                    }
                }
                R.id.imgCheck ->{
                    mAdapter.data[position].isCheck= !mAdapter.data[position].isCheck
                    mAdapter.notifyItemChanged(position)
                    binding.tvBtnCheck.text="确定("+setCheckNum().size.toString()+")"
                }
            }
        }
        initRefreshLayout()
        pageNo = 1
        getListData()
    }

    /** 选择好的id **/
    fun setCheckNum():MutableList<String>{

        var mList = arrayListOf<String>()
        for (i in mAdapter.data.indices){
            if (mAdapter.data[i].isCheck)
                mList.add(mAdapter.data[i].uid)
        }
        return mList

    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    override fun initData() {
        super.initData()
        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                binding.etSearch.clearFocus()
                hideKeyboard(binding.etSearch)
                pageNo = 1
                getListData()
            }
        }
        binding.tvBtnCheck.setSingleClickListener {
            var counts=setCheckNum()
            if (counts.size>0){
                showLoading()
                chatDataBean?.let {
                    if(it.price>0){
                        XPopup.Builder(this@ChatListActivity)
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                            .asCustom(
                                ConfirmCancelPopViiew(
                                    this@ChatListActivity, it.tips,  "正在创建，确定要继续吗？",
                                    btnConfirm = {
                                       if(it.jifen>0){
                                           XPopup.Builder(this@ChatListActivity)
                                               .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                                               .customHostLifecycle(lifecycle)
                                               .autoOpenSoftInput(true)
                                               .moveUpToKeyboard(true)
                                               .dismissOnTouchOutside(false)
                                               .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                               .asCustom(
                                                   PayPwdPopViiew(this@ChatListActivity,object :
                                                       PayPwdPopViiew.SublickListener{
                                                       override fun onAdopt( pwdStr: String) {
                                                           //送礼物
                                                           crtGroup(pwdStr,counts)
                                                       }
                                                   })
                                               )
                                               .show()
                                       }else{
                                           showToast("余额不足啦～")
                                       }
                                    },
                                    btnCancel = {
                                    },
                                )
                            )
                            .show()
                    }else{
                        crtGroup("",counts)
                    }
                }







            }else showToast("请选择您的好友进群")
        }
    }


    private fun crtGroup( paypassword:String,counts:MutableList<String>){
        var str= StringUtil.convertListToString(counts)
        val map: HashMap<String, Any> = HashMap()
        map["name"] = name
        map["classify_id"] = classify_id
        map["fuids"] = str.toString()
        map["paypassword"] = paypassword
        loge("创建群聊="+ GsonUtil.mapToJsonStrObj(map))
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onCrtGroupMethod(it1) }
    }

    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] = keyword
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onFriendListMethod(it1) }
    }


    var bean : UserRyResult?=null

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ChatListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast( it)
            }
            againLoginMsg.observe(this@ChatListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

            onCrtGroupData.observe(this@ChatListActivity){
                //创建群成功
                dismissLoading()
                //跳转到会话页面
                RouterUtils.startToJumpGoup(this@ChatListActivity,it.data.data.tid)
                finish()
            }
            onFriendListData.observe(this@ChatListActivity, Observer {
                //我的好友列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                chatDataBean =it.data.data
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData( it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData( it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            })


        }
    }

    inner  class ChatListAdapter (sign:Int)   : BaseQuickAdapter<ChatDataResultBean, BaseViewHolder>(
        R.layout.friends_item) {

        var sign:Int=0

        init {
            this.sign=sign
        }


        override fun convert(helper: BaseViewHolder, item: ChatDataResultBean) {
            GlideUtil.ImageHeadLoad(this.context,item.headimg,helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName,item.nickname)
            var textStatus=helper.getView<RoundTextView>(R.id.tvBtnNext)
            //1 双方都通过   -1显示等待通过状态 -2 显示通过 按钮
            if (item.status==1)
                textStatus.visibility= View.GONE
            else if (item.status==-1){
                textStatus.visibility= View.VISIBLE
                textStatus.text="等待通过"
                textStatus.delegate.backgroundColor=this.context.getCompatColor(R.color.btn_lvse)
            }else if (item.status==-2){
                textStatus.visibility= View.VISIBLE
                textStatus.text="通过"
                textStatus.delegate.backgroundColor=this.context.getCompatColor(R.color.btn_default_color)
            }else textStatus.visibility= View.GONE
            if (sign==1){
                if (item.status==1){
                    if(item.uid==CustKey.CHAT_SYSY_ID){
                        helper.setGone(R.id.imgCheck,true)
                    }else{
                        helper.setGone(R.id.imgCheck,false)
                        helper.getView<ImageView>(R.id.imgCheck).setImageResource(
                            if(item.isCheck)  R.mipmap.icon_cb_default_checked
                            else R.mipmap.icon_cb_default_not_checked)
                    }
                }
            }else helper.setGone(R.id.imgCheck,true)
        }
    }


}